<template>
  <div class="create-post-container">
    <div class="create-post-wrapper">
      <!-- 返回按钮 -->
      <div class="back-button" @click="goBack">
        <el-icon><ArrowLeft /></el-icon>
        <span>返回</span>
      </div>

      <h1 class="page-title">发布帖子</h1>

      <div class="content-container">
        <!-- 左侧编辑区域 -->
        <div class="left-content">
          <!-- 标题输入 -->
          <div class="input-group">
            <div class="input-label">标题</div>
            <el-input
              v-model="postTitle"
              placeholder="请输入标题"
              maxlength="50"
              show-word-limit
            />
          </div>

          <!-- 富文本编辑器 -->
          <div class="input-group">
            <div class="input-label">正文</div>
            <client-only>
              <div class="editor-container">
                <div id="editor"></div>
              </div>
            </client-only>
          </div>

          <!-- 附件上传 -->
          <div class="input-group">
            <div class="input-label">附近资料分享</div>
            <div class="upload-container">
              <div class="upload-area">
                <el-icon><Upload /></el-icon>
                <div class="upload-text">点击或拖拽文件到此处上传</div>
                <div class="upload-tip">支持 .zip .pdf .doc .docx 等格式文件</div>
                <input
                  type="file"
                  class="file-input"
                  multiple
                  @change="handleFileUpload"
                />
              </div>
            </div>
          </div>

          <!-- 已上传文件列表 -->
          <div class="file-list" v-if="uploadedFiles.length > 0">
            <div class="file-item" v-for="(file, index) in uploadedFiles" :key="index">
              <div class="file-info">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-size">大小: {{ formatFileSize(file.size) }}</div>
              </div>
              <div class="file-actions">
                <el-icon class="delete-icon" @click="removeFile(index)"
                  ><Delete
                /></el-icon>
              </div>
            </div>
          </div>

          <!-- 封面图片上传 -->
          <div class="input-group">
            <div class="input-label">封面图片</div>
            <div class="cover-upload">
              <div class="cover-preview" v-if="coverImage">
                <img :src="coverImage" alt="封面预览" />
                <div class="cover-actions">
                  <el-icon class="delete-icon" @click="removeCover"><Delete /></el-icon>
                </div>
              </div>
              <div class="cover-upload-area" v-else>
                <el-icon><Picture /></el-icon>
                <div class="upload-text">点击上传封面图片</div>
                <input
                  type="file"
                  class="file-input"
                  accept="image/*"
                  @change="handleCoverUpload"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧设置区域 -->
        <div class="right-content">
          <!-- 帖子设置 -->
          <div class="settings-card">
            <h3 class="card-title">帖子设置</h3>

            <!-- 帖子分类 -->
            <div class="setting-item">
              <div class="setting-label">选择分类</div>
              <el-select v-model="postCategory" placeholder="请选择分类">
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <!-- 帖子标签 -->
            <div class="setting-item">
              <div class="setting-label">添加标签</div>
              <el-select
                v-model="postTags"
                multiple
                collapse-tags
                collapse-tags-tooltip
                placeholder="请选择标签"
              >
                <el-option
                  v-for="item in tagOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <!-- 发布设置 -->
            <div class="setting-item">
              <div class="setting-label">发布设置</div>
              <el-radio-group v-model="publishType">
                <el-radio :label="1">立即发布</el-radio>
                <el-radio :label="2">定时发布</el-radio>
              </el-radio-group>
              <el-date-picker
                v-if="publishType === 2"
                v-model="publishTime"
                type="datetime"
                placeholder="选择发布时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                :disabled-date="disabledDate"
                class="date-picker"
              />
            </div>
          </div>

          <!-- 发布须知 -->
          <div class="notice-card">
            <h3 class="card-title">发布须知</h3>
            <div class="notice-content">
              <p>1. 请勿发布违反法律法规的内容</p>
              <p>2. 请勿发布侵犯他人知识产权的内容</p>
              <p>3. 请勿发布广告、垃圾信息</p>
              <p>4. 请勿发布色情、暴力等不良信息</p>
              <p>5. 违反规定的内容将被删除，严重者将被封号</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作栏 -->
      <div class="bottom-actions">
        <div class="word-count">当前字数：{{ currentWordCount }}</div>
        <div class="action-buttons">
          <el-button @click="saveAsDraft">保存草稿</el-button>
          <el-button type="primary" @click="publishPost">发布</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { ArrowLeft, Upload, Delete, Picture } from "@element-plus/icons-vue";

const router = useRouter();

// 帖子信息
const postTitle = ref("");
const postContent = ref("");
const postCategory = ref("");
const postTags = ref([]);
const publishType = ref(1);
const publishTime = ref("");
const currentWordCount = ref(0);
const uploadedFiles = ref([]);
const coverImage = ref("");
let editor = null;

// 分类选项
const categoryOptions = ref([
  { value: "gmat", label: "GMAT" },
  { value: "gre", label: "GRE" },
  { value: "ea", label: "EA" },
  { value: "other", label: "其他" },
]);

// 标签选项
const tagOptions = ref([
  { value: "material", label: "资料包" },
  { value: "question", label: "真题" },
  { value: "experience", label: "经验分享" },
  { value: "strategy", label: "备考攻略" },
  { value: "discussion", label: "讨论" },
]);

// 返回上一页
const goBack = () => {
  if (postTitle.value || postContent.value || uploadedFiles.value.length > 0) {
    if (confirm("您有未保存的内容，确定要离开吗？")) {
      router.back();
    }
  } else {
    router.back();
  }
};

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

// 处理文件上传
const handleFileUpload = (event) => {
  const files = event.target.files;
  if (files) {
    for (let i = 0; i < files.length; i++) {
      uploadedFiles.value.push(files[i]);
    }
  }
  // 清空input，允许重复上传相同文件
  event.target.value = "";
};

// 移除文件
const removeFile = (index) => {
  uploadedFiles.value.splice(index, 1);
};

// 处理封面上传
const handleCoverUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      coverImage.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
  // 清空input，允许重复上传相同文件
  event.target.value = "";
};

// 移除封面
const removeCover = () => {
  coverImage.value = "";
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toFixed(2) + " " + sizes[i];
};

// 保存为草稿
const saveAsDraft = () => {
  if (editor) {
    postContent.value = editor.getHTML();
  }

  // 这里添加保存草稿的逻辑
  alert("草稿已保存");
};

// 发布帖子
const publishPost = () => {
  if (!postTitle.value) {
    alert("请输入标题");
    return;
  }

  if (editor) {
    postContent.value = editor.getHTML();
  }

  if (!postContent.value || postContent.value === "<p></p>") {
    alert("请输入正文内容");
    return;
  }

  if (!postCategory.value) {
    alert("请选择分类");
    return;
  }

  // 这里添加发布帖子的逻辑
  alert("帖子发布成功");
  router.push("/forum");
};

// 更新字数统计
const updateWordCount = () => {
  if (editor) {
    const text = editor.getText();
    currentWordCount.value = text.length;
  }
};

onMounted(() => {
  // 使用 setTimeout 确保在客户端渲染时初始化编辑器
  setTimeout(() => {
    if (process.client && document.getElementById("editor")) {
      // 这里应该引入并初始化你项目中已有的富文本编辑器
      // 以下是一个示例，实际使用时需要替换为你项目中的编辑器
      try {
        // 模拟编辑器初始化
        editor = {
          getHTML: () => "<p>编辑器内容</p>",
          getText: () => "编辑器内容",
          on: (event, callback) => {
            // 模拟事件监听
            if (event === "text-change") {
              // 模拟内容变化时更新字数
              setTimeout(() => {
                callback();
              }, 100);
            }
          },
        };

        // 监听内容变化，更新字数
        if (editor) {
          editor.on("text-change", updateWordCount);
        }
      } catch (error) {
        console.error("初始化编辑器失败:", error);
      }
    }
  }, 0);
});

onBeforeUnmount(() => {
  // 清理编辑器实例
  editor = null;
});
</script>

<style scoped lang="scss">
// 提取公共变量
$primary-color: #126983;
$secondary-color: #18404b;
$text-color: #333;
$light-text-color: #666;
$border-color: #eee;
$background-color: #ecf4f2;
$card-background: #f9f9f9;
$border-radius: 8px;
$box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
.create-post-container {
  display: flex;
  justify-content: center;
  padding: 20px;
  background-color: $background-color;
  min-height: 100vh;
}

.create-post-wrapper {
  width: 1000px; // 修改宽度为1000px
  background-color: #fff;
  border-radius: $border-radius;
  box-shadow: $box-shadow;
  padding: 20px;
  margin: 0 auto; // 确保居中
}
.editor-container {
  border: 1px solid $border-color;
  border-radius: $border-radius;
  min-height: 300px;
}

.upload-area {
  border: 2px dashed $border-color;
  border-radius: $border-radius;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  position: relative;

  &:hover {
    border-color: $primary-color;
  }

  .upload-text {
    font-size: 16px;
    margin: 10px 0;
  }

  .upload-tip {
    font-size: 12px;
    color: $light-text-color;
  }

  .file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
}

.file-list {
  margin-top: 15px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: $card-background;
  border-radius: $border-radius;
  margin-bottom: 10px;
  border: 1px solid #cccccc;

  &:last-child {
    margin-bottom: 0;
  }
}

.file-info {
  display: flex;
  flex-direction: column;
}

.file-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.file-size {
  font-size: 12px;
  color: $light-text-color;
}

.file-actions {
  .delete-icon {
    color: #f56c6c;
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }
}

.cover-upload {
  width: 100%;
}

.cover-upload-area {
  border: 2px dashed $border-color;
  border-radius: $border-radius;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  position: relative;

  &:hover {
    border-color: $primary-color;
  }

  .upload-text {
    font-size: 16px;
    margin: 10px 0;
  }

  .file-input {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
  }
}

.cover-preview {
  width: 100%;
  height: 200px;
  position: relative;
  border-radius: $border-radius;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .cover-actions {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    width: 30px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;

    .delete-icon {
      color: #fff;
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }
    }
  }
}

.settings-card {
  background-color: #fff;
  border-radius: $border-radius;
  box-shadow: $box-shadow;
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 15px;
  color: $text-color;
}

.setting-item {
  margin-bottom: 15px;

  &:last-child {
    margin-bottom: 0;
  }
}

.setting-label {
  font-size: 14px;
  margin-bottom: 10px;
  color: $text-color;
}

.date-picker {
  width: 100%;
  margin-top: 10px;
}

.notice-card {
  background-color: #fff;
  border-radius: $border-radius;
  box-shadow: $box-shadow;
  padding: 20px;
}

.notice-content {
  font-size: 14px;
  line-height: 1.6;
  color: $text-color;

  p {
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.bottom-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20px;
  border-top: 1px solid $border-color;
}

.word-count {
  font-size: 14px;
  color: $light-text-color;
}

.action-buttons {
  display: flex;
  gap: 15px;
}
</style>
